package org.example.StudentManagementSystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.example.StudentManagementSystem.entity.Enrollment;
import org.example.StudentManagementSystem.common.Result;
import org.example.StudentManagementSystem.dto.request.EnrollmentDTO;
import org.example.StudentManagementSystem.service.CourseService;
import org.example.StudentManagementSystem.service.EnrollmentService;
import org.example.StudentManagementSystem.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/enrollment")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
@Tag(name = "选课管理", description = "选课管理相关接口")
public class EnrollmentController {
    @Autowired
    private EnrollmentService enrollmentService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private CourseService courseService;

    /**
     * 将Enrolment转换为EnrollmentDTO
     */
    public EnrollmentDTO convertToDTO(Enrollment enrollment) {
        EnrollmentDTO enrollmentDTO = new EnrollmentDTO();
        BeanUtils.copyProperties(enrollment, enrollmentDTO);
        if (enrollment.getStudentId() != null) {
            enrollmentDTO.setStudentName(studentService.getById(enrollment.getStudentId()).getName());
        }
        if (enrollment.getCourseId() != null) {
            enrollmentDTO.setCourseName(courseService.getById(enrollment.getCourseId()).getName());
        }
        return enrollmentDTO;
    }

    /**
     * 获取选课记录
     */
    @Operation(summary = "获取选课记录", description = "根据分页参数获取选课记录列表")
    @ApiResponse(responseCode = "200", description = "获取选课记录成功",
            content = @Content(array = @ArraySchema(schema = @Schema(implementation = EnrollmentDTO.class))))
    @GetMapping("")
    public Result getEnrollmentList(
            @Parameter(description = "页码", required = true) @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小", required = true) @RequestParam(defaultValue = "10") int size) {
        Page<Enrollment> enrollmentPage = enrollmentService.page(Page.of(page, size));
        if (enrollmentPage.getTotal() == 0) {
            return Result.error("暂无数据");
        }
        List<EnrollmentDTO> enrollmentDTOList = enrollmentPage.getRecords().stream().map(this::convertToDTO).collect(Collectors.toList());
        Page<EnrollmentDTO> enrollmentDTOPage = new Page<>();
        enrollmentDTOPage.setCurrent(enrollmentPage.getCurrent());
        enrollmentDTOPage.setSize(enrollmentPage.getSize());
        enrollmentDTOPage.setTotal(enrollmentPage.getTotal());
        enrollmentDTOPage.setRecords(enrollmentDTOList);
        return Result.success(enrollmentDTOPage, "获取选课记录成功");
    }

    /**
     * 获取全部选课记录
     */
    @Operation(summary = "获取全部选课记录", description = "获取所有选课记录")
    @ApiResponse(responseCode = "200", description = "获取全部选课记录成功",
            content = @Content(array = @ArraySchema(schema = @Schema(implementation = EnrollmentDTO.class))))
    @GetMapping("/all")
    public Result getAllEnrollment() {
        List<Enrollment> enrollmentList = enrollmentService.list();
        if (enrollmentList.isEmpty()) {
            return Result.error("暂无数据");
        }
        List<EnrollmentDTO> enrollmentDTOList = enrollmentList.stream().map(this::convertToDTO).collect(Collectors.toList());
        return Result.success(enrollmentDTOList, "获取全部选课记录成功");
    }

    /**
     * 获取单个选课记录
     */
    @Operation(summary = "获取单个选课记录", description = "根据ID获取单个选课记录")
    @ApiResponse(responseCode = "200", description = "获取选课记录成功",
            content = @Content(schema = @Schema(implementation = EnrollmentDTO.class)))
    @GetMapping("/{id}")
    public Result getEnrollmentById(
            @Parameter(description = "选课记录ID", required = true) @PathVariable int id) {
        Enrollment enrollment = enrollmentService.getById(id);
        if (enrollment == null) {
            return Result.error("选课记录不存在");
        }
        EnrollmentDTO enrollmentDTO = convertToDTO(enrollment);
        return Result.success(enrollmentDTO, "获取选课记录成功");
    }

    /**
     * 添加选课记录
     */
    @Operation(summary = "添加选课记录", description = "添加新的选课记录")
    @ApiResponse(responseCode = "200", description = "选课记录添加成功",
            content = @Content(schema = @Schema(implementation = Enrollment.class)))
    @PostMapping("")
    public Result addEnrollment(
            @Parameter(description = "选课记录信息", required = true) @RequestBody Enrollment enrollment) {
        if (enrollment.getStudentId() == null || enrollment.getCourseId() == null) {
            return Result.error("选课信息不完整");
        }
        return enrollmentService.save(enrollment) ? Result.success(enrollment, "选课记录添加成功") : Result.error("选课记录添加失败");
    }

    /**
     * 修改选课记录
     */
    @Operation(summary = "修改选课记录", description = "根据ID修改选课记录")
    @ApiResponse(responseCode = "200", description = "选课记录修改成功",
            content = @Content(schema = @Schema(implementation = Enrollment.class)))
    @PutMapping("/{id}")
    public Result updateEnrollment(
            @Parameter(description = "选课记录ID", required = true) @PathVariable int id,
            @Parameter(description = "新的选课记录信息", required = true) @RequestBody Enrollment enrollment) {
        if (enrollment.getStudentId() == null || enrollment.getCourseId() == null) {
            return Result.error("选课信息不完整");
        }
        enrollment.setId(id);
        return enrollmentService.updateById(enrollment) ? Result.success(enrollment, "选课记录修改成功") : Result.error("选课记录修改失败");
    }

    /**
     * 删除选课记录
     */
    @Operation(summary = "删除选课记录", description = "根据ID删除选课记录")
    @ApiResponse(responseCode = "200", description = "选课记录删除成功")
    @DeleteMapping("/{id}")
    public Result deleteEnrollment(
            @Parameter(description = "选课记录ID", required = true) @PathVariable int id) {
        if (enrollmentService.getById(id) == null) {
            return Result.error("选课记录不存在");
        }
        return enrollmentService.removeById(id) ? Result.success("选课记录删除成功") : Result.error("选课记录删除失败");
    }

    /**
     * 批量删除选课记录
     */
    @Operation(summary = "批量删除选课记录", description = "根据ID列表批量删除选课记录")
    @ApiResponse(responseCode = "200", description = "批量删除选课记录成功")
    @DeleteMapping("")
    public Result deleteEnrollments(
            @Parameter(description = "选课记录ID列表", required = true) @RequestBody int[] ids) {
        if (ids.length == 0) {
            return Result.error("请选择要删除的记录");
        }
        for (int id : ids) {
            if (enrollmentService.getById(id) == null) {
                return Result.error("选课记录不存在");
            }
        }
        List<Integer> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        return enrollmentService.removeBatchByIds(idList) ? Result.success("批量删除选课记录成功") : Result.error("批量删除选课记录失败");
    }

}
